const app = getApp();
import { addToCart, getAddressList } from '../../../utils/requestApi.js'

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    goodsInfo: Object,
    prDid: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    imgUrl: app.data.imgurl,
    defaultSku:{}, //规格默认数据
    specsData: [], // 规格数据
    goodsNum: 1,  //物品数量
    hiddenModal: true, // 打开specs modal
    hiddenModalAni: true, // 打开动画
    combineIdArr: [], // 选择项后 组成的id
    selectedArr: [], // 已选
    selectedStr: '', // 已选(转换成字符串)))
    animationData: {}, // 加购动画
    aniImg: null, //动画图片
    hiddenAni: true, // 加购动画显示
    address: null, //配送地址
  },
  
  ready:function(){
    console.log(this.data.goodsInfo)
    this.initData();
    this.getAddress();
  },

  /**
   * 组件的方法列表
   */
  methods: {
    
    //初始化页面数据
    initData(){
      let { combineIdArr, selectedArr, goodsInfo, specsData } = this.data;
      goodsInfo.SkuItem.forEach(item =>{
        item.Values.forEach(item2 =>{item.status = false})
      })
      let obj = {
        ImageUrl: goodsInfo.ImageUrl,
        SalePrice: goodsInfo.MarketPrice,
        NeedPoint: goodsInfo.NeedPoint,
        NeedPrice: goodsInfo.NeedPrice,
        Stock: goodsInfo.Stock || 20,
        ProductId: this.data.prDid,
        SkuId: goodsInfo.SkuItem.length == 0 ? goodsInfo.SkuReferralPrice[0].SkuId:'',
        ChangeType: goodsInfo.ChangeType
      }
      this.setData({
        defaultSku: obj,
        specsData: goodsInfo.SkuItem,
        combineIdArr: new Array(goodsInfo.SkuItem.length),
        selectedArr: new Array(goodsInfo.SkuItem.length)
      })
    },

    //获取收货地址 
    getAddress() {
      getAddressList().then(res => {
        if (res.data.Status == 'Success' && res.data.Data != '[]') {
          res.data.Data.forEach(item => {
            if (item.IsDefault) this.setData({ address: item.FullAddress })
            else this.setData({ address: res.data.Data[0].FullAddress })
          })
        }
      })
    },
    
    // 改变数量
    changeNum(e){
      let { type } = e.currentTarget.dataset;
      let { defaultSku, goodsNum } = this.data;
      if (type == 0 && goodsNum != 1) this.setData({ goodsNum: goodsNum - 1 })
      if (type == 1) {
        console.log(goodsNum, defaultSku.Amount)
        if (!defaultSku.Amount) defaultSku.Amount = 999999;
        if (goodsNum < defaultSku.Stock && goodsNum < defaultSku.Amount) this.setData({ goodsNum: goodsNum + 1 })
        else if (goodsNum >= defaultSku.Amount) wx.showToast({ icon: 'none', title: '不能超过限购数量', })
        else wx.showToast({ icon: 'none', title: '库存不足', })
      }
    },

    // 规格选择
    selectSpecs(e){
      let { attributeid, valueid, value, index } = e.currentTarget.dataset;
      let { specsData, goodsInfo, combineIdArr, selectedArr, defaultSku } = this.data;
      specsData.forEach(item =>{
        if (attributeid == item.AttributeId){
          item.Values.forEach(item2 =>{
            if (item2.ValueId == valueid) {
              item2.status = true;
              selectedArr[index] = value;
              combineIdArr[index] = valueid;
            }
            else item2.status = false;
          })
        }
        this.setData({ specsData, selectedArr, selectedStr: selectedArr.join(' '), combineIdArr })
      })
      let skuId = defaultSku.ProductId + '_' + combineIdArr.join('_');

      for (let attrName in goodsInfo.Sku){
        if (attrName == skuId){
          defaultSku.SalePrice = goodsInfo.Sku[attrName].NeedPrice;
          defaultSku.Amount = goodsInfo.Sku[attrName].Amount;
          defaultSku.Stock = goodsInfo.Sku[attrName].Stock;
          defaultSku.NeedPoint = goodsInfo.Sku[attrName].NeedPoint;
          defaultSku.NeedPrice = goodsInfo.Sku[attrName].NeedPrice;
          defaultSku.SkuId = attrName;
          this.setData({ defaultSku, goodsNum: 1 })
        }
      }
    },
    
    // 打开 关闭 showModal
    showModal(e){
      if (e) { //点击已选那里的时候
        if (e.currentTarget.dataset.type == 'general') wx.setStorageSync('ctype', 'sign')
      }
      this.setData({
        aniImg: this.data.goodsInfo.ImageUrl1,
        hiddenModal: !this.data.hiddenModal
      });
      setTimeout(() =>{
        this.setData({
          hiddenModalAni: !this.data.hiddenModalAni
        });
      },200)
    },
      
    // 添加购物车
    addGoods(e){
      let { combineIdArr, goodsNum, defaultSku, goodsInfo  } = this.data;
      if (combineIdArr.filter((item) => item && item.toString().trim).length != goodsInfo.SkuItem.length ){
        wx.showToast({
          icon: 'none',
          title: '请选择商品规格'
        })
        return
      }
      this.showModal();
      addToCart({
        SkuID: combineIdArr.length == 0 ? defaultSku.SkuId : goodsInfo.DefaultSku.ProductId + '_' + combineIdArr.join('_'),
        Quantity: goodsNum
      }).then(res =>{
        if (res.data.ErrorCode == 401) {
          wx.showToast({
            icon: 'none',
            title: res.data.ErrorMsg,
          })
        }
        if(res.statusCode == 200) this.myAni();
      })
    },

    // 立即购买 
    immediatelyBuy(){
      let { combineIdArr, goodsNum, goodsInfo, defaultSku } = this.data;
      if (combineIdArr.filter(Boolean).length != goodsInfo.SkuItem.length) {
        wx.showToast({
          icon: 'none',
          title: '请选择完整商品规格'
        })
        return
      }
      this.showModal();
      
      let obj = {
        productSku: defaultSku.SkuId,
        fromPage: 'signbuy', // 活动类型 （购买类型）
        buyAmount: goodsNum,
        orderType: 'GiftOrder',
        changeType: defaultSku.ChangeType
      }
      wx.navigateTo({
        url: `../confirmationOfOrder/confirmationOfOrder?obj=${JSON.stringify(obj)}`
      })
    },

    //点击确定
    confirm(e) {
      if (wx.getStorageSync('ctype') == 'add') this.addGoods();
      else if (wx.getStorageSync('ctype') == 'sign' || wx.getStorageSync('ctype') == 'group') this.immediatelyBuy();
      else this.showModal();
    },

    //加购动画
    myAni() {
      this.setData({ hiddenAni: false })
      const animation = wx.createAnimation({
        duration: 1000,
        timingFunction: 'ease',
      })
      animation.opacity(1).scale(1.5, 1.5).step({ duration: 300 });
      animation.scale(0.2, 0.2).step();
      animation.translate(-320, 1500).opacity(0).step({ duration: 200 });
      this.setData({
        animationData: animation.export()
      })
      // 1.5秒后复位动画
      setTimeout(() => {
        animation.opacity(1).translate(0, 0).step();
        this.setData({
          aniImg: '',
          animationData: animation.export()
        })
      }, 1500)
    },
  }
})
